package cn.zhuzicc.basic.jvm.t2;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * @author zhaoxiang
 * @version 1.0
 * @description 弱引用示例
 * -Xmx20m -XX:+PrintGCDetails -verbose:gc
 * @Date 2021/9/20 18:07
 */
public class Demo2_5 {

    static final int _4M = 4 * 1024 * 1024;

    public static void main(String[] args) {
//        test();
        test1();
    }

    /**
     * 循环 i 1...9
     */
    public static void test() {
        List<WeakReference<byte[]>> list = new ArrayList<>();

        for (int i = 0; i < 9; i++) {
            WeakReference<byte[]> ref = new WeakReference<>(new byte[_4M]);
            list.add(ref);
            for (WeakReference<byte[]> w : list) {
                System.out.print(w.get() + "  ");
            }
            System.out.println();
        }
        System.out.println("循环结束" + list.size());
    }

    /**
     * 循环 i 10...n
     */
    public static void test1() {
        List<WeakReference<byte[]>> list = new ArrayList<>();

        /*
            循环10次的时候，list中的软引用对象只有最后一个指向了对象，
            前9个全部被GC回收，因为弱引用对象本身也需要消耗内存。
         */
        for (int i = 0; i < 10; i++) {
            WeakReference<byte[]> ref = new WeakReference<>(new byte[_4M]);
            list.add(ref);
            for (WeakReference<byte[]> w : list) {
                System.out.print(w.get() + "  ");
            }
            System.out.println();
        }
        System.out.println("循环结束" + list.size());
    }
}
